// -------------------------------------------------
// BlinKit - BlinKit Library
// -------------------------------------------------
//   File Name: qjs_progress_element.cpp
// Description: Bindings for HTMLProgressElement
//      Author: Ziming Li
//     Created: 2022-07-12
// -------------------------------------------------
// Copyright (C) 2022 MingYang Software Technology.
// -------------------------------------------------

#include "./qjs_bindings.h"

#include "blinkit/blink/renderer/bindings/core/qjs/qjs.h"
#include "blinkit/blink/renderer/bindings/core/qjs/qjs_c_function_list_entries.h"
#include "blinkit/blink/renderer/core/html/HTMLProgressElement.h"

/**
 * https://developer.mozilla.org/en-US/docs/Web/API/HTMLProgressElement
 */

using namespace blink::HTMLNames;

namespace BlinKit {
namespace qjs {

static JSValue GetMax(JSContext *ctx, JSValueConst thisVal)
{
    HTMLProgressElement *progress = ScriptWrappable::Cast<HTMLProgressElement>(thisVal);
    return JS_NewFloat64(ctx, progress->max());
}

static JSValue GetValue(JSContext *ctx, JSValueConst thisVal)
{
    HTMLProgressElement *progress = ScriptWrappable::Cast<HTMLProgressElement>(thisVal);
    return JS_NewFloat64(ctx, progress->value());
}

static JSValue SetMax(JSContext *ctx, JSValueConst thisVal, JSValueConst maxValue)
{
    HTMLProgressElement *progress = ScriptWrappable::Cast<HTMLProgressElement>(thisVal);

    double d;
    if (0 != JS_ToFloat64(ctx, &d, maxValue))
        return JS_ThrowTypeError(ctx, "Invalid max value");

    progress->setMax(d);
    return JS_UNDEFINED;
}

static JSValue SetValue(JSContext *ctx, JSValueConst thisVal, JSValueConst value)
{
    HTMLProgressElement *progress = ScriptWrappable::Cast<HTMLProgressElement>(thisVal);

    double d;
    if (0 != JS_ToFloat64(ctx, &d, value))
        return JS_ThrowTypeError(ctx, "Invalid value");

    progress->setValue(d);
    return JS_UNDEFINED;
}

JSValue CreateProgressElementPrototype(JSContext *ctx, JSValue elementPrototype)
{
    static const JSCFunctionListEntry Funcs[] = {
        CGetSetEntry("max", GetMax, SetMax),
        CGetSetEntry(Strings::Value, GetValue, SetValue)
    };

    JSValue ret = JS_NewObjectProto(ctx, elementPrototype);
    JS_SetPropertyFunctionList(ctx, ret, Funcs, std::size(Funcs));
    return ret;
}

} // namespace qjs
} // namespace BlinKit
